<?php
/**
 * Created by PhpStorm.
 * User: janke
 * Date: 17-3-19
 * Time: 下午9:43
 */

namespace app\models;

use yii\db\ActiveRecord;
use yii\helpers\Url;
use yii\web\Linkable;
use yii\web\Link;
use yii\web\UserEvent;


class Message extends ActiveRecord implements Linkable
{
    public $messageSender;
    public $messageContent;
    public $messagePicUrl;
    public $messageIsFake;
    public $messageFakeName;

    /**
     * 数据表名
     * @return string
     * @author Janke
     */
    public static function tableName()
    {
        return 'message'; // TODO: Change the autogenerated stub
    }

    /**
     * 数据验证规则
     * @return array
     * @author Janke
     */
    public function rules()
    {
        return [
            [['messageSender', 'messageContent', 'messageIsFake'], 'required'],
            ['messageSender', 'validateMessageSender'],
            ['messageIsFake', 'validateMessageIsFake'],
        ]; // TODO: Change the autogenerated stub
    }

    public function validateMessageSender($attribute, $params = null)
    {
        if (User::findByUsername($this->messageSender) == null)
        {
            $this->addError("error", "messageSender not found");
        }
        if (User::$accessToken)
        {
            if ($user = User::findUserDataByAccessToken(User::$accessToken))
            {
                if ($user['userName'] != $this->messageSender)
                {
                    $this->addError("error", "messageSender and accessTaken are not same");
                }
            }
        }
    }

    public function validateMessageIsFake($attribute, $params)
    {
        if (!($this->messageIsFake == 1 || $this->messageIsFake == 0))
        {
            $this->addError("error", "messageIsFake must be 1 or 0");
        }
    }

    /**
     * 重命名api的显示字段名
     * @return array
     * @author Janke
     */
    public function fields()
    {
        return [
            'messageId' => 'id',
            'messageContent' => 'content',
            'messagePicUrl' => 'picture',
            'messageTime' => 'time',
            'messageIsFake' => 'isfake',
//            'messageFakeName' => 'fakename',
            'messageSender' => 'username',
            'messageCommentCount' => 'comment_count',
            'messageApproveCount' => 'approve_count',
            'messageDisapproveCount' => 'disapprove_count',
//            '' => function ($model) {
//                return $model->id;
//            }
        ]; // TODO: Change the autogenerated stub
    }

    /**
     * 在数据段中增加message详情的链接
     * @return array
     * @author Janke
     */
    public function getLinks()
    {
        return [
            Link::REL_SELF => Url::to(["comment/message/$this->id"], true),
        ];
    }

    /**
     * 根据messageId获取message信息
     * @param $messageId
     * @return array
     * @author Janke
     */
    public static function getMessageById($messageId)
    {
        $message = Message::findOne($messageId);
        $message = $message->attributes;
        $fields = Message::fields();
        $data = [];
        foreach ($fields as $key => $value)
        {
            $data[$key] = $message[$value];
        }
        return $data;
    }

    /**
     * 插入一条message
     * @return bool|int
     * @author Janke
     */
    public function insertMessage()
    {
        $rest =\Yii::$app->db->createCommand()->insert('message', [
            'username' => $this->messageSender,
            'content' => $this->messageContent,
            'picture' => $this->messagePicUrl,
        ])->execute();
        return $rest ? $rest : false;
    }

    /**
     * 查找 id 为 messageId 的 message 并删除
     * @param $messageId
     * @return false|int
     * @author Janke
     */
    public function deleteMessageById($messageId)
    {
        $message = Message::findOne(['id' => $messageId]);
        $user = User::findUserDataByAccessToken(User::$accessToken);
        $deleteResult = 0;
        if ($message->attributes['username'] == $user['userName'] && $message)
        {
            $deleteResult = $message->delete();
        }
        else
        {
            $message ? null : $this->addError("error", "message not found");
            $message->attributes['username'] == $user['userName'] ? null : $this->addError("error", "this user have not power to delete");
        }
        return $deleteResult;
    }

    /**
     * 评论条数自增
     * @param $messageId
     * @return bool|static
     * @author Janke
     */
    public static function updateCommentCount($messageId)
    {
        // message comment count ++
        $messageModel = Message::findOne(['id' => $messageId]);
        $messageModel->comment_count += 1;
        $result = $messageModel->update(false);
        return $result ? $messageModel : false;
    }

    public static function downDateCommentCount($messageId)
    {
        $messageModel = Message::findOne(['id' => $messageId]);
        $messageModel->comment_count -= 1;
        $result = $messageModel->update(false);
        return $result ? $messageModel : false;
    }

}